﻿using Dm.filter;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WLYT.Application.Interfaces;
using WLYT.Core;
using WLYT.Domain.Entries;
using WLYT.Domain.Model;

namespace WLYT.Application.Services
{
    public class HttpWebService(IHttpClientFactory httpClientFactory, IRepository<LogRecord> logRecordRepository) : IHttpWebService
    {
        public async Task<T> HttpGetAsync<T>(string url, int timeOut = 10, bool isLog = true)
        {
            DateTime now = DateTime.Now;
            Stopwatch watch = new();
            string result = string.Empty;
            try
            {
                var client = httpClientFactory.CreateClient();
                client.Timeout = new TimeSpan(0, 0, timeOut);
                HttpResponseMessage response = await client.GetAsync(url);
                result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return JsonConvert.DeserializeObject<T>(result);
                }
                else
                {
                    throw new Exception(result);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"HttpGet:{url} Error", ex);
            }
            finally
            {
                watch.Stop();
                if (isLog)
                {
                    result = result ?? "";
                    await logRecordRepository.SplitTableInsertAsync(new LogRecord
                    {
                        Method = "POST",
                        RequestUri = "Warehouse.SendTask",
                        CreateTime = now,
                        RequestContent = result,
                        ResponseContent = result,
                        Timer = (int)watch.ElapsedMilliseconds,
                        IsSuccess = result.Contains("\"Code\":0") || result.Contains("\"success\":true") || result.Contains("\"state\":1") || result.Contains("\"respCode\":1000")
                    });
                }
            }
        }

        public async Task<T> HttpPostAsync<T>(string url, object postData = null, int timeOut = 10, bool isLog = true)
        {
            DateTime now = DateTime.Now;
            Stopwatch watch = new();
            string requestContent = JsonConvert.SerializeObject(postData ?? "");
            var client = httpClientFactory.CreateClient();
            client.Timeout = new TimeSpan(0, 0, timeOut);
            using (HttpContent httpContent = new StringContent(requestContent, Encoding.UTF8))
            {
                string result = string.Empty;
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    result = await response.Content.ReadAsStringAsync();
                    if (response.IsSuccessStatusCode)
                    {
                        return JsonConvert.DeserializeObject<T>(result);
                    }
                    else
                    {
                        throw new Exception(result);
                    }
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                    throw new Exception($"HttpPost:{url} Error", ex);
                }
                finally
                {
                    watch.Stop();
                    if (isLog)
                    {
                        result = result ?? "";
                        await logRecordRepository.SplitTableInsertAsync(new LogRecord
                        {
                            Method = "POST",
                            RequestUri = "Warehouse.SendTask",
                            CreateTime = now,
                            RequestContent = requestContent,
                            ResponseContent = result,
                            Timer = (int)watch.ElapsedMilliseconds,
                            IsSuccess = result.Contains("\"Code\":0") || result.Contains("\"success\":true") || result.Contains("\"state\":1") || result.Contains("\"respCode\":1000")
                        });
                    }
                }
            }
        }
    }
}
